package com.haotian.mail.uitl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class _MimeUtil {
	private static Session session;

	static {
		// 发送邮件的环境属性
		final Properties props = new Properties();

		props.setProperty("mail.transport.protocol", "");

		props.setProperty("mail.host", "");

		props.setProperty("mail.smtp.auth", "");// 请求身份认证

		session = Session.getInstance(props);
	}

	/**
	 * 老版本兼容
	 * <p>
	 * </p>
	 * 
	 * @deprecated
	 * @param fromUser
	 * @param sendToUser
	 * @param ccUser
	 * @param bccUser
	 * @param in
	 * @return
	 * @throws MessagingException
	 */
	public static MimeMessage newMimeMessage(String fromUser, String sendToUser, String ccUser, String bccUser,
			InputStream in) throws MessagingException {

		MimeMessage message = null;

		if (null != in) {
			message = new MimeMessage(session, in);
		} else {
			message = new MimeMessage(session);
		}

		if (null != fromUser) {
			InternetAddress iaformUser = null;
			iaformUser = new InternetAddress(fromUser);
			message.setFrom(iaformUser);
		}

		if (null != sendToUser) {
			InternetAddress[] iatoUser = new InternetAddress[] { new InternetAddress(sendToUser) };
			message.setRecipients(RecipientType.TO, iatoUser);
		} else if (null == in) {
			throw new MessagingException("501 Invalid Address");
		}

		if (null != ccUser) {
			// 设置抄送
			InternetAddress[] iaCcUser = new InternetAddress[] { new InternetAddress(ccUser) };
			message.setRecipients(RecipientType.CC, iaCcUser);
		}

		if (null != bccUser) {
			// 设置密送，其他的收件人不能看到密送的邮件地址
			InternetAddress[] iaBccUser = new InternetAddress[] { new InternetAddress(bccUser) };
			message.setRecipients(RecipientType.BCC, iaBccUser);
		}

		return message;
	}

	public static MimeMessage newMimeMessage(String fromUser, String fromAlias, String[] sendToUser, String[] ccUser,
			String[] bccUser, InputStream in) throws MessagingException {

		MimeMessage message = null;

		if (null != in) {
			message = new MimeMessage(session, in);
		} else {
			message = new MimeMessage(session);
		}

		if (null != fromUser) {
			InternetAddress iaformUser = null;
			// 设置别名
			if (null != fromAlias) {
				try {
					iaformUser = new InternetAddress(fromUser, fromAlias, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// 因为考虑到老版本兼容性 固使用异常传递 无需修改方法
					throw new MessagingException("UnsupportedEncodingException", e);
				}
			} else {
				iaformUser = new InternetAddress(fromUser);
			}
			message.setFrom(iaformUser);
		}

		if (null != sendToUser && sendToUser.length > 0) {
			InternetAddress[] iatoUser = new InternetAddress[sendToUser.length];

			for (int i = 0; i < sendToUser.length; i++) {
				iatoUser[i] = new InternetAddress(sendToUser[i]);
			}

			message.setRecipients(RecipientType.TO, iatoUser);

		} else if (null == in) {
			throw new MessagingException("501 Invalid Address");
		}

		if (null != ccUser && ccUser.length > 0) {
			// 设置抄送
			InternetAddress[] iaCcUser = new InternetAddress[ccUser.length];

			for (int i = 0; i < ccUser.length; i++) {
				iaCcUser[i] = new InternetAddress(ccUser[i]);
			}

			message.setRecipients(RecipientType.CC, iaCcUser);
		}

		if (null != bccUser && bccUser.length > 0) {
			// 设置密送，其他的收件人不能看到密送的邮件地址
			InternetAddress[] iaBccUser = new InternetAddress[bccUser.length];

			for (int i = 0; i < bccUser.length; i++) {
				iaBccUser[i] = new InternetAddress(bccUser[i]);
			}

			message.setRecipients(RecipientType.BCC, iaBccUser);
		}

		return message;
	}

	/**
	 * 老版本兼容方法
	 * 
	 * @deprecated
	 */
	public static MimeMessage createTextMime(String fromUser, String sendToUse, String ccUser, String bccUser,
			String title, String Text, String charset) throws MessagingException {
		MimeMessage message = newMimeMessage(fromUser, null, new String[] { sendToUse }, new String[] { ccUser },
				new String[] { bccUser }, null);
		// 设置邮件标题
		message.setSubject(title, charset);
		// 设置邮件的内容体
		message.setText(Text, charset);
		return message;
	}

	/**
	 * 创建文本内容邮件的MimeMessage 对象
	 *
	 * @author 494009061@qq.com
	 *         <p/>
	 * @date 2017年7月20日
	 * @param fromUser
	 * @param fromAlias
	 * @param sendToUse[]
	 * @param ccUser[]
	 * @param bccUser[]
	 * @param title
	 * @param Text
	 * @param charset
	 * @return MimeMessage
	 * @throws MessagingException
	 */
	public static MimeMessage createTextMime(String fromUser, String fromAlias, String[] sendToUse, String[] ccUser,
			String[] bccUser, String title, String Text, String charset) throws MessagingException {
		MimeMessage message = newMimeMessage(fromUser, null, sendToUse, ccUser, bccUser, null);
		// 设置邮件标题
		message.setSubject(title, charset);
		// 设置邮件的内容体
		message.setText(Text, charset);
		return message;
	}

	/**
	 * 利用mime 格式的 文件字节数组 创建 MimeMessage
	 *
	 * @author haotianrich@outlook.com
	 *         <p/>
	 * @date 2017年7月20日
	 * @param emlBuffer
	 * @return
	 * @throws MessagingException
	 * @throws IOException
	 */
	public static MimeMessage createMimeByByteArray(byte[] emlBuffer) throws MessagingException, IOException {
		ByteArrayInputStream in = new ByteArrayInputStream(emlBuffer);
		MimeMessage message = newMimeMessage(null, null, null, null, null, in);
		in.close();
		return message;
	}

	/**
	 * 创建HTML格式的邮件MimeMessage 对象 老版本兼容方法
	 * 
	 * @deprecated
	 */
	public static MimeMessage createHtmlMime(String fromUser, String sendToUse, String ccUser, String bccUser,
			String title, String content, String charset) throws MessagingException {
		// 获取mime
		MimeMessage message = newMimeMessage(fromUser, null, new String[] { sendToUse }, new String[] { ccUser },
				new String[] { bccUser }, null);
		// 创建一个Multipart 用于存储，存于HTML内容的 BodyPart
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();

		// html内容 存入 BodyPart
		html.setContent(content, "text/html; charset=" + charset);
		// BodyPart 存入 Multipart
		mainPart.addBodyPart(html);

		message.setSubject(title, charset);
		// Multipart 存入 消息中
		message.setContent(mainPart);
		return message;
	}

	/**
	 * 创建HTML格式的邮件MimeMessage 对象
	 *
	 * @author haotianrich@outlook.com
	 *         <p/>
	 * @date 2017年7月20日
	 * @param fromUser
	 * @param fromAlias
	 * @param sendToUse[]
	 * @param ccUser[]
	 * @param bccUser[]
	 * @param title
	 * @param content
	 * @param charset
	 * @return
	 * @throws MessagingException
	 */
	public static MimeMessage createHtmlMime(String fromUser, String fromAlias, String[] sendToUse, String[] ccUser,
			String[] bccUser, String title, String content, String charset) throws MessagingException {
		// 获取mime
		MimeMessage message = newMimeMessage(fromUser, fromAlias, sendToUse, ccUser, bccUser, null);
		// 创建一个Multipart 用于存储，存于HTML内容的 BodyPart
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();

		// html内容 存入 BodyPart
		html.setContent(content, "text/html; charset=" + charset);
		// BodyPart 存入 Multipart
		mainPart.addBodyPart(html);

		message.setSubject(title, charset);
		// Multipart 存入 消息中
		message.setContent(mainPart);
		return message;
	}

	/**
	 * 检测邮件中是否包含 真附件
	 * 
	 * @param part
	 * @return
	 * @throws Exception
	 */
	public static boolean isContainAttach(MimeMessage message) throws Exception {

		boolean attachflag = false;

		Object o = message.getContent();

		Multipart multipart = null;

		if (o instanceof Multipart) {
			multipart = (Multipart) o;

			for (int i = 0; i < multipart.getCount(); i++) {
				BodyPart mpart = multipart.getBodyPart(i);
				String disposition = mpart.getDisposition();
				if (disposition != null && disposition.equals(Part.ATTACHMENT)) {
					attachflag = true;
					break;
				}
			}
		}
		return attachflag;
	}

	/**
	 * 给传入的MimeMessage 加入附件，附件形式为java.io.File[] 数组对象
	 * 
	 * @author 494009061@qq.com
	 *         <p/>
	 * @date 2017年7月19日
	 * @param message
	 * @param file
	 * @return
	 * @throws MessagingException
	 * @throws IOException
	 */
	public static void setFileToMimeMessage(MimeMessage message, File[] files) throws MessagingException, IOException {

		Object o = message.getContent();
		Multipart multipart = null;
		if (o instanceof Multipart)
			multipart = (Multipart) o;
		else
			multipart = new MimeMultipart();

		for (File file : files) {
			BodyPart attachmentBodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(file);
			attachmentBodyPart.setDataHandler(new DataHandler(source));
			attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
			multipart.addBodyPart(attachmentBodyPart);
			message.setContent(multipart);
		}

	}

	/**
	 * 老版本添加附件的兼容方法
	 * 
	 * @deprecated
	 */
	public static void setFileToMimeMessage(MimeMessage message, File file) throws MessagingException, IOException {
		setFileToMimeMessage(message, new File[] { file });
	}
	
}
